package com.cskaoyan.controller;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.vo.AdminStorageCreateVO;
import com.cskaoyan.service.AdminStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author zhuqiushi
 * @since 2022/09/09 14:58
 */
@RestController
@RequestMapping("wx/storage")
public class WxStorageController {
    //由于处理逻辑完全一致，直接复用admin的storage
    @Autowired
    AdminStorageService adminStorageService;
    @Value("${spring.web.resources.static-locations}")
    String staticLocations;

    /*
     * /wx/storage/upload
     * POST
     * */
    @RequestMapping("upload")
    public BaseRespVo<AdminStorageCreateVO> upload(MultipartFile file) throws IOException {
        //首先获取名字
        String originalFilename = file.getOriginalFilename();
        //获取size
        long size = file.getSize();
        //获取type
        String contentType = file.getContentType();
        //将其存到本地
        String[] uuids = UUID.randomUUID().toString().split("-");
        String uuid = uuids[0] + uuids[1];
        //小程序端已经自动做了映射处理
        String key = originalFilename;
        File receiveFile = new File(staticLocations.substring(5), key);
        if (!receiveFile.getParentFile().exists()) {
            receiveFile.getParentFile().mkdirs();
        }
        file.transferTo(receiveFile);
        //获取url
        String url="http://localhost:8083/wx/storage/fetch/" + key;
        //将其插入表中
        AdminStorageCreateVO adminStorageCreateVO = new AdminStorageCreateVO();
        adminStorageCreateVO.setType(contentType);
        adminStorageCreateVO.setSize((int) size);
        adminStorageCreateVO.setUrl(url);
        adminStorageCreateVO.setName(originalFilename);
        adminStorageCreateVO.setKey(key);
        adminStorageService.create(adminStorageCreateVO);
        BaseRespVo ok = BaseRespVo.ok(adminStorageCreateVO);
        return ok;
    }
}
